<template>
	<view class="l-svga" v-if="sources.svgaSrc" :style="{'z-index':zIndex}">
		<view class="svgaContent" :style="svgaStyle.positionStyle">
			<c-svga ref="cSvgaRef" :height="svgaStyle.height" :width="svgaStyle.width" :src="sources.svgaSrc" :loops='1'
				:auto-play="true" @frame='onFrame' @finished='onFinished' @percentage='onPercentage'
				@loaded='onLoaded'></c-svga>
		</view>

	</view>
</template>

<script>
	export default {
		props: {
			zIndex: {
				type: [Number, String],
				default: 999999999999
			}
		},
		data() {
			return {
				isInit: false,
				style: "width:100vw;height:100vh;position:absolute;top:0rpx;left:0rpx",
				show: false,
				svgaOpacity: 1,
				hasPlayNow: false,
				sources: {
					svgaSrc: "",
					audioSrc: ""
				},
				lastPlaySvgSrc: "",
				lastPlayAudioSrc: "",
				audioContext: {},
				destroyAudioContenxt: null,
				aduioContextList: [],

				dataQueue: [], //任务队列
				isProcessing: false, // 当前是否在处理任务
				currentTask: '', // 当前正在处理的任务

			}
		},
		computed: {

			svgaStyle() {
				// 开始按钮除了定位之外的其他样式
				const allowedKeys = ["position", "left", "top", "right", "bottom", "transform"];
				let filteredPart = [];
				let nonFilteredPart = [];
				let width = "";
				let height = "";
				let styleStr = this.style;

				if (styleStr) {
					styleStr.split(";").forEach((entry) => {
						const trimmedEntry = entry.trim();
						if (allowedKeys.some((key) => trimmedEntry.startsWith(key))) {
							filteredPart.push(trimmedEntry);
						} else {
							// 提取 width 和 height，但不从 nonFilteredPart 中删除
							if (trimmedEntry.startsWith("width")) {
								width = trimmedEntry.split(":")[1].trim();
							}
							if (trimmedEntry.startsWith("height")) {
								height = trimmedEntry.split(":")[1].trim();
							}
							if (trimmedEntry) {
								nonFilteredPart.push(trimmedEntry);
							}
						}
					});
					return {
						positionStyle: filteredPart.join(";"),
						otherStyle: nonFilteredPart.join(";"),
						width: width,
						height: height
					};
				} else {
					return {
						positionStyle: "",
						otherStyle: "",
						width: "",
						height: ""
					};
				}
			}
		},
		mounted() {

		},
		methods: {

			playSvga(data) {
				console.log("触发播放", data);
				this.dataQueue.push(data)
				if (!this.isProcessing) {
					this.processNextTask();
				}
			},
			// 处理下一个任务
			processNextTask() {
				if (this.dataQueue.length === 0) {
					this.isProcessing = false; // 如果队列为空，标记为未处理
					return;
				}

				// 从队列中取出下一个任务
				this.currentTask = this.dataQueue.shift(); // 取出并移除队列中的第一个任务
				this.isProcessing = true; // 标记为正在处理

				this.playSvgaFun(this.currentTask)

				// 模拟任务处理，可以替换为实际的处理逻辑

				// // 这里使用 setTimeout 来模拟任务处理的延时
				// setTimeout(() => {
				//   this.taskCompleted(); // 任务完成后调用回调
				// }, 2000); // 假设每个任务处理需要 2 秒
			},

			changeSvgaStyle(data) {
				console.log("svga初始化");
				if (data) {
					this.style = data
				}
			},
			// 初始化播放
			initPlay(data) {
				this.isInit = true
				this.svgaOpacity = 0
				this.playSvgaFun(data)
				console.log("触发初始化");
			},
			initAudioContext() {
				return new Promise((resolve, reject) => {
					if (this.sources.audioSrc) {
						const context = uni.createInnerAudioContext()
						context.src = this.sources.audioSrc
						if (this.destroyAudioContenxt) {
							this.destroyAudioContenxt.destroy()
							console.log("赋值前先销毁");
						}
						this.audioContext = context
						this.lastPlayAudioSrc = this.sources.audioSrc
						this.aduioContextList.push(context)
						// console.log(this.aduioContextList, "音频上下文列表");
						resolve(true)
					} else {
						reject(false)
					}

				})

			},
			playClickVoice() {
				if (this.audioContext) {
					console.log("1");
					// this.audioContext.stop()
					this.audioContext.play()
				} else {
					this.initAudioContext().then(res => {
						console.log("2");
						this.audioContext.play()

					})
				}
			},
			async playSvgaFun(data) {
				if (data.svgaSrc && !this.hasPlayNow) {
					let flag = (this.lastPlaySvgSrc === data.svgaSrc) && (data.svgaSrc)
					if (flag) {
						this.play()
						this.hasPlayNow = true
						this.playVoice(data)
					} else {
						let obj = {
							svgaSrc: "",
							audioSrc: ""
						}
						obj.svgaSrc = data.svgaSrc
						obj.audioSrc = data.audioSrc
						if (this.$refs.cSvgaRef) {
							this.stop()
							this.clear()
						}
						this.sources = {
							...obj
						}
						this.lastPlaySvgSrc = obj.svgaSrc
						this.hasPlayNow = true
						if (data.needLate) {
							console.log("需要延迟");
							setTimeout(() => {
								this.playVoice(data)
							}, 200)
						} else {
							this.playVoice(data)
						}

					}


				}
			},
			playVoice(data) {

				console.log("进入音频播放", data);


				let flag2 = (this.lastPlayAudioSrc === data.audioSrc)
				if (flag2 && data.audioSrc) {
					this.playClickVoice()
				} else if (flag2 && !data.audioSrc) {
					this.audioContext = null
				} else if (!flag2 && data.audioSrc) {
					this.audioContext = null
					console.log("进入情况3", data);
					this.sources.audioSrc = data.audioSrc
					this.playClickVoice()
				} else {
					console.log("3");
				}

			},
			play() {
				this.$refs.cSvgaRef.call('startAnimation')
			},
			// 反向播放
			playRev() {
				this.$refs.cSvgaRef.call('startAnimation', true)
			},
			// 暂停
			pause() {
				this.$refs.cSvgaRef.call('pauseAnimation')
			},
			// 停止
			stop() {
				this.$refs.cSvgaRef.call('stopAnimation')
			},
			clear() {
				this.$refs.cSvgaRef.call('clear')
			},
			jumpTo(percent) {
				this.$refs.cSvgaRef.call('stepToPercentage', [percent, true])
			},
			onFrame() {

			},
			onFinished() {
				this.svgaOpacity = 1
				this.hasPlayNow = false
				this.stop()
				this.clear()

				if (this.audioContext) {
					if (this.aduioContextList.length >= 4) {
						this.handleClearAduioContextList()
					}
					this.audioContext = null
				}
				this.currentTask = ''; // 清空当前任务
				this.isProcessing = false; // 标记为未处理
				if (!this.isInit) {
					this.$emit('played')
				} else {
					this.isInit = false
				}


				// 继续处理下一个任务
				this.processNextTask();
			},
			handleClearAduioContextList() {
				let list = this.aduioContextList.slice(0, 2)
				list.forEach((item, index) => {
					item.destroy()
				})
				this.aduioContextList.splice(0, 2)
			},
			clearSvga() {
				console.log("清除调用");
				this.stop()
				this.clear()
				this.dataQueue = []
				this.isProcessing = false
				this.hasPlayNow = false
				this.svgaOpacity = 1
				// this.sources = {
				// 	svgaSrc: "",
				// 	audioSrc: ""
				// }


			},
			cleanSvgaSource() {
				this.sources = {
					svgaSrc: "",
					audioSrc: ""
				}

			},
			onPercentage() {

			},
			onLoaded() {}
		}
	}
</script>

<style lang="scss" scoped>
	.l-svga {
		position: absolute;
		left: 0;
		top: 0;
		width: 100vw;
		height: 100vh;
		z-index: 999999999999;
		pointer-events: none;
		overflow: hidden;

		.svgaContent {
			position: absolute;
			pointer-events: none;
		}
	}
</style>